<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>兄弟组件之间通信</title>
    <script src="vue.js"></script>
  </head>
  <body>
    <div id="app">
      <app-com1></app-com1>
      <app-com2></app-com2>
    </div>
    <script>
      var bus = new Vue();
      var comNode1 = Vue.extend({
        template:
          '<div><button @click="change">单击给兄弟组件传值</button></div>',
        methods: {
          change: function () {
            //通过空实例去触发emit
            bus.$emit("posttobrother", 123);
          },
        },
      });
      var comNode2 = Vue.extend({
        template: "<div>来自兄弟组件的值为：{{ datafrombrother }}</div>",
        data() {
          return {
            datafrombrother: "",
          };
        },
        mounted: function () {
          //接收emit事件
          bus.$on(
            "posttobrother",
            function (val) {
              this.datafrombrother = val;
            }.bind(this)
          );
        },
      });
      // 创建根实例
      var vm = new Vue({
        el: "#app",
        components: {
          "app-com1": comNode1,
          "app-com2": comNode2,
        },
      });
    </script>
  </body>
</html>
